package cn.vcjf.washcar.common.util.weixin;

import cn.vcjf.washcar.common.util.DateUtils;
import cn.vcjf.washcar.common.util.SysParamUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class WechatAccessToken {
	private static Logger log = Logger.getLogger(WechatAccessToken.class);
	private static String Wechat_Accesstoken="";
	private static String Wechat_ActiveTime="";
	private static String Errcode="";
	private static String Errmsg="";
	
	public static String get() {
		return Wechat_Accesstoken;
	}
	public static void setAccesstoken(String accesstoken) {
		Wechat_Accesstoken = accesstoken;
	}
	public static void setActiveTime(String activeTime) {
		Wechat_ActiveTime = activeTime;
	}
	public static String getActiveTime() {
		return Wechat_ActiveTime;
	}
	public static String getErrcode() {
		return Errcode;
	}
	public static String getErrmsg() {
		return Errmsg;
	}
	private static final WechatAccessToken Token=new WechatAccessToken();
	
	private WechatAccessToken(){}
	
	public static WechatAccessToken getInstance() throws IOException, ParseException{
		SimpleDateFormat sdd= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String time= DateUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm:ss");
		String activeTime="";
		if(StringUtils.isBlank(get())){
			activeTime="2018/07/23 17:00:00";
		}else{
			activeTime=Wechat_ActiveTime;
		}
		Long nowTime=sdd.parse(time).getTime();
		Long effectTime=sdd.parse(activeTime).getTime();
		effectTime=effectTime+2*60*60*1000;
		log.info("获取当前凭证：["+get()+"]生效截止时间:["+sdd.format(new Date(effectTime))+"]");
		if(nowTime >= effectTime){
			log.info("当前凭证已失效,正在获取新的凭证");
			JSONObject result=GetAccess();
			if(result.containsKey("access_token")){
				setAccesstoken(result.getString("access_token"));
				setActiveTime(result.getString("Effective"));
				log.info("获取到凭证：【"+get()+"】当前时间：【"+getActiveTime()+"】");
			}else if(result.containsKey("errcode")){
				Errcode=result.getString("errcode");
				Errmsg=result.getString("errmsg");
				log.info("获取凭证失败："+Errmsg);
			}else{
				log.info("获取凭证异常："+Errmsg);
			}
		}
		return Token;
	}
	private static JSONObject GetAccess() throws IOException, ParseException{
		JSONObject jsonObject=new JSONObject();
        String requestUrlString = SysParamUtil.getParam("vc.wechat.accessurl").replace("APPID", SysParamUtil.getParam("vc.wechat.gzh.appid")).replace("APPSECRET", SysParamUtil.getParam("vc.wechat.gzh.appsecret"));//将请求用户的URL中的///参数替换成真正的内容
        URL url = new URL(requestUrlString);  //创建url连接
        log.debug("GetAccess创建url连接");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //打开连接
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestMethod("GET");
        urlConnection.setUseCaches(false);
        urlConnection.connect();
        log.debug("GetAccess开始解析响应");
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        String result = buffer.toString();
        log.debug("GetAccess解析响应完成，result："+result);
        jsonObject = JSON.parseObject(result); //将服务器返回的字符串转换成json格式
        String Time= DateUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm:ss");//获取当前时间
        jsonObject.put("Effective", Time);
		return jsonObject;
	}

}
